import { ChatConversation } from "./block/chat_conversation"
import { ChatContent } from "./block/chat_content"
import { createContext, useEffect, useState } from "react"
import { useDispatch, useSelector } from "react-redux";
import http from "../../http";
import { openMessage } from "../../store/features/message";
import { ContactsModel } from "./components/contacts_model";
import { GroupNotice } from "./components/group_notice";


export const ChatContext = createContext<any>({});

export const Chat: React.FC<any> = ({ topRef }) => {
    const { list, current } = useSelector((state: any) => state.conversation.value);


    const { user } = useSelector((state: any) => state.user.value);
    const dispatch = useDispatch();
    const [isFristLogin, setIsFristLogin] = useState(false);


    useEffect(() => {
        // 解决第一次进入页面，没有数据的问题
        if (list.length > 0) {
            if (!isFristLogin) {
                setIsFristLogin(true);
                const fetchMessage = async () => {
                    const respones = await http.get("/message/list?targetId=" + list[current].targetId)
                    dispatch(openMessage({ messages: respones.data, targetId: list[current].targetId }));
                    console.log("请求完成")
                }
                fetchMessage();

            }
        }
    }, [list])


    const [visibleGroup, setVisibleGroup] = useState(false);

    // create invitation 等
    const [contactsModelState, setContactsModelState] = useState("create");

    const createGroup = () => {
        setContactsModelState('create');
        setVisibleGroup(true);
    }

    const invitationGroupUser = () => {
        setContactsModelState('invitation');
        setVisibleGroup(true);
    }

    const [members, setMembers] = useState([]);

    const removeGroupUser = (list: any) => {
        setContactsModelState('remove');
        setVisibleGroup(true);
        const newList = list.filter((item: any) => item.userId != user.userId);
        setMembers(newList);
    }


    const [groupNoticeVisible, setGroupNoticeVisible] = useState(false);


    const [groupDrawerVisible, setGroupDrawerVisible] = useState(false);

    const [groupInfo, setGroupInfo] = useState<any>();

    const openGroupNoticeModel = (group:any) => {
        setGroupInfo(group);
        setGroupNoticeVisible(true);
    }

    return (
        <ChatContext.Provider value={{ groupDrawerVisible, setGroupDrawerVisible,visibleGroup, setVisibleGroup, contactsModelState, createGroup, invitationGroupUser, removeGroupUser, members, topRef, groupNoticeVisible, setGroupNoticeVisible,openGroupNoticeModel,groupInfo }}>
            <GroupNotice />
            <ContactsModel />
            <div className="flex flex-row w-full">
                <ChatConversation />
                <ChatContent topRef={topRef} />
            </div>
        </ChatContext.Provider>
    )
}
